package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.ImportResult;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.exception.LogicOverException;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void saveOrUpdate(Employee employee,Long[] ids)  {
        if (employee.getId() == null) {
            //先保存会设置主键
            employeeMapper.insert(employee);
        } else {
            //先清空旧关系再关联新关系
            employeeMapper.deleteRelation(employee.getId());
            //修改员工信息
            employeeMapper.updateByPrimaryKey(employee);
        }
        //关联新关系
        if(ids != null && ids.length > 0){
            employeeMapper.saveRelation(employee.getId(),ids);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if(id != null){
            //先删除中间表关系
            employeeMapper.deleteRelation(id);
            //删除员工
            employeeMapper.deleteByPrimaryKey(id);
        }
    }

    //批量删除员工
    @Override
    @Transactional
    public void deleteList(Long[] ids) {
        if(ids != null && ids.length > 0){
            //先删除中间表关系
            employeeMapper.deleteRelationList(ids);
            //删除员工
            employeeMapper.deleteList(ids);
        }
    }

    @Override
    public Employee selectOne(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> selectAll() {
        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        //先使用分页的插件,监听下一行SQL查询代码,自动根据qo去分页查询
        //并封装到PageInfo中(代替原来的pageResult)
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employeeList = employeeMapper.queryPage(qo);
        return new PageInfo<>(employeeList);
    }

    @Override
    public Employee checkLogin(String username, String password) {
        //Spring提供的判空工具方法hasText会自动帮忙去除前后空格
        if (!StringUtils.hasText(username)){
            //取反表示没有文本就才执行
            throw new LogicException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }

        Employee employee = employeeMapper.selectLogin(username, password);

        if(employee == null){
            throw new LogicOverException("用户名或者密码错误");
        }

        if(!(employee.isStatus())){
            throw new LogicException("该用户名已经被禁用");
        }

        //说明账号正常登录,把这个账号未读的公告数量查询出来
        int count = employeeMapper.selectUnRead(employee.getId());
        employee.setUnReadCount(count);

        return employee;
    }

    @Override
    public boolean checkUsername(String username) {
        Employee employee = employeeMapper.selectByUsername(username);
        return employee==null;
    }

    @Override
    public Workbook exportXls(QueryObject qo) {
        //创建Workbook对象,该依赖包是XSSF类型的
        Workbook wb = new XSSFWorkbook();

        //创建表
        Sheet sheet = wb.createSheet("员工名单");

        //标题行写内容
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("真实姓名");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("年龄");

        //查询员工并写在单元格
        //同时高级查询以后也可以只保存高级查询的,此时也用分页高级分页查询的方法,但不使用分页插件监听即可
        List<Employee> employeeList = employeeMapper.queryPage(qo);
        //遍历
        for (int i = 0; i < employeeList.size(); i++) {
            Employee employee = employeeList.get(i);
            //创建行,由于第一行(0)已经被标题行占用了,从i+1开始
            Row row1 = sheet.createRow(i+1);
            //写入单元格
            row1.createCell(0).setCellValue(employee.getUsername());
            row1.createCell(1).setCellValue(employee.getName());
            row1.createCell(2).setCellValue(employee.getEmail());
            row1.createCell(3).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    @Transactional
    public ImportResult importXls(MultipartFile file) throws IOException {
        //记录成功/失败条数
        int successCount = 0;
        int failCount = 0;
        //保存错误信息的list
        List<String> list = new ArrayList<>();
        //保存成功保存的id
        List<Long> successId = new ArrayList<>();

        /*//获取所有部门的名称和id
        departmentMapper.selectImport();*/

        //根据传进来的文件创建Workbook对象
        Workbook wb = new XSSFWorkbook(file.getInputStream());
        //读取第一张表
        Sheet sheet = wb.getSheetAt(0);
        //获取有数据的最后一行的索引
        int lastRowNum = sheet.getLastRowNum();

        //遍历读取表中信息,标题行不读取,所以从索引1开始
        for (int i = 1; i <= lastRowNum ; i++) {
            //创建对象用于封装
            Employee employee = new Employee();
            //读取行信息
            Row row = sheet.getRow(i);

            //读取列并封装到对象中
            String username = row.getCell(0).getStringCellValue();
            employee.setUsername(username);
            employee.setName(row.getCell(1).getStringCellValue());
            employee.setEmail(row.getCell(2).getStringCellValue());

            //由于年龄是数字(也有些人在excel设置错误变成文本格式,需要判断)
            //先获取年龄的那个单元格,然后判断里面内容的类型
            Cell cell = row.getCell(3);

            if(cell.getCellType() == CellType.NUMERIC){
                //获取数值类型的单元格内容
                double cellValue = cell.getNumericCellValue();
                employee.setAge((int)cellValue);
            }else{
                //获取文本格式的单元格内容
                String age = cell.getStringCellValue();
                employee.setAge(Integer.valueOf(age));
            }

            //根据部门名称存入部门id
            String deptName = row.getCell(4).getStringCellValue();
            Department department = departmentMapper.selectByName(deptName);
            if(department != null){
                employee.setDept(department);
            }

            //设置默认密码和管理员和状态
            employee.setPassword("1");
            employee.setAdmin(false);
            employee.setStatus(true);

            //先查询用户名是否已经存在
            if(employeeMapper.selectByUsername(employee.getUsername()) == null){
                //不存在则插入
                employeeMapper.insert(employee);
                successId.add(employee.getId());
                successCount++;
            }else{
                failCount++;
                int count = i+1;
                list.add("第" + count +"行:" + username + "该用户名已经存在");
            }
        }
        if(failCount == 0){
            return new ImportResult();
        }
        employeeMapper.deleteImport(successId);
        return new ImportResult(false,successCount,failCount,list);
    }

    @Override
    public void changeStatus(Long id, boolean status) {
        employeeMapper.changeStatus(id,status);
    }
}
